<?php

namespace Beerus\Modules\BrandLevel\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\cache\brand\LevelRights as cLevelRights;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brandRights\BrandLevelRightsConfig;
use Biz\model\brandRights\BrandRightsSource;
use Biz\service\brand\BrandLevel as sBrandLevel;
use Biz\service\BrandRights\BrandLevelRightsConfigService;
use Biz\service\BrandRights\BrandLevelSourceRightsService;
use Biz\service\BrandRights\BrandRightsSourceService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

class LevelController extends Controller
{

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        $params = $request->all();
        $levelId = isset($params['level']) && $params['level'] != '' ? $params['level'] : null;
        $host = $request->getHost();
        $host = str_replace('beerus', 'frieza', $host);
        $friezaUrl = $request->getScheme() . '://' . $host . '/admin/task/index/1';
        $brandLevels = sBrandLevel::levelList();
        if (isset($levelId)) {
            $brandLevels = [$brandLevels[$levelId]];
        }
        $gridModel = new GridDataModel($brandLevels);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $friezaUrl) {
            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('level', '等级')
                        ->select(sBrandLevel::BRAND_LEVELS);
                });
                //$filter->expand();//默认展开
            });
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->column('id', '等级id');
            $grid->column('name', '等级名称');
            $grid->column('value_range', '成长值范围')->display(function ($value_range) {
                [$start, $end] = $value_range;
                if ($this->id == sBrandLevel::BRAND_LEVEL_TOP) {
                    return '>= ' . $start;
                } else {
                    return $start . ' - ' . $end;
                }
            });
            $grid->setActionClass(Actions::class);
            $grid->actions(function (Grid\Displayers\Actions $actions) use ($friezaUrl) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();

                $link = "/admin/BrandLevel/index/" . $actions->row->id;

                $html_set = ' <a class="fa fa-edit" data-id="' . $actions->row->id . '" href="' . $friezaUrl . '" target="_blank" style="margin-right: 5px">
                                    <span class="glyphicon" aria-hidden="true">设置任务集</span></a>';
                $actions->append($html_set);
                $html_set = ' <a class="fa fa-edit" data-id="' . $actions->row->id . '" href="' . $link . '" style="margin-right: 5px">
                                    <span class="glyphicon" aria-hidden="true">设置权益集</span></a>';
                $actions->append($html_set);

            });
        });

        $content->row($grid);

        return $content
            ->header('等级信息')
            ->description(' ')
            ->breadcrumb(['text' => '等级信息', 'url' => '/BrandLevel/index']);
    }

    /**
     * 等级权益
     * @param int $level
     * @param Content $content
     * @return Content
     */
    public function rights(Request $request, int $level, Content $content): Content
    {
        Admin::script($this->setJsScript());
        $params = $request->all();
        $where = $this->_getWhere($params);
        $list = BrandLevelRightsConfigService::levelSourceRightsConfig($level, $where);
        $gridModel = new GridDataModel($list);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $allSourceRights
                            = BrandLevelSourceRightsService::getLevelSourceRights();
                        $allSourceRightsKv = array_column($allSourceRights,
                            'rights_title', 'source_rights_id');
                        $filter->equal('id', '权益id')
                            ->select($allSourceRightsKv);
                        $filter->equal('rights_name', '权益英文标识')
                            ->placeholder('权益英文标识');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('rights_type', '权益类型')
                            ->select(BrandRightsSource::RIGHTS_TYPE_ARR);
                        $filter->equal('rights_on', '状态')
                            ->select(BrandRightsSource::STATUS_ARR);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableCreateButton();
                $grid->disablePagination();
                //$grid->disableFilter();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', '权益id')->width(60);
                $grid->column('rights_title', '权益名称')->width(100);
                $grid->column('rights_name', '权益英文名称')->copyable()->width(200);
                $grid->column('rights_type', '权益类型')->using(
                    BrandRightsSource::RIGHTS_TYPE_ARR
                    , '未知')->label([
                    BrandRightsSource::RIGHTS_TYPE_OPEN => 'warning',
                    BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM => 'info',
                    BrandRightsSource::RIGHTS_TYPE_NUM => 'success',
                    BrandRightsSource::RIGHTS_TYPE_OTHER => 'default',
                ])->width(100);

                $grid->column('rights_data', "数量")->display(function (
                    $rights_data,
                    $column
                ) {
                    if ($this->rights_type
                        == BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM || $this->rights_type == BrandRightsSource::RIGHTS_TYPE_NUM
                    ) {
                        if ($this->rights_on == BrandLevelRightsConfig::STATUS_NORMAL) {
                            return $column->editable();
                        } else {
                            return '';
                        }

                    }

                    return '/';
                })->width(100);

                $grid->column('rights_desc', '权益描述')->width(300);

                // 设置text、color、和存储值
                $states = [
                    'on' => [
                        'value' => 1,
                        'text' => '启用',
                        'color' => 'primary'
                    ],
                    'off' => [
                        'value' => 0,
                        'text' => '停用',
                        'color' => 'default'
                    ],
                ];

                $grid->column('rights_on', "状态")->switch($states)->width(110);
                $grid->disableActions();

            }
        );

        $content->row($grid);

        return $content
            ->header('等级【' . sBrandLevel::BRAND_LEVELS[$level] . '】权益信息')
            ->description(' ')
            ->breadcrumb(
                [
                    'text' => '等级信息',
                    'url' => '/BrandLevel/index'
                ],
                [
                    'text' => '等级【' . sBrandLevel::BRAND_LEVELS[$level] . '】权益信息',
                ]
            );
    }


    private function _getWhere($params)
    {
        $where = [];
        if (isset($params['id']) && $params['id']) {
            $where['id'] = $params['id'];
        }
        if (isset($params['rights_name']) && $params['rights_name']) {
            $where['rights_name'] = $params['rights_name'];
        }
        if (isset($params['rights_type']) && $params['rights_type']) {
            $where['rights_type'] = $params['rights_type'];
        }
        if (isset($params['rights_on']) && $params['rights_on'] != '' && !is_null($params['rights_on'])) {
            $where['rights_on'] = $params['rights_on'];
        }
        return $where;
    }

    /**
     * 开启权益
     * @param int $level
     * @param int $rights_on
     * @return \Illuminate\Http\JsonResponse
     */
    public function rightsSwitch(int $level, int $sourceRightsId, Request $request)
    {
        $params = $request->all();

        try {

            if (!cLevelRights::canWriteLevelRightsCfg($level, $sourceRightsId)) {
                throw new \Exception('当前操作已锁定，请联系技术人员');
            }

            $labels = ['关闭', '开启'];

            $status = $params['rights_on'] == 1 ? 1 : 0;
            $bRet = BrandLevelRightsConfigService::setOneLevelRightsConfig($level, $sourceRightsId, $status);

            if (!$bRet) {
                throw new \Exception('权益' . $labels[$status] . '失败！');
            }
            $success = [
                'message' => '操作成功',
                'code' => 1,
                'status' => true,
            ];

            cLevelRights::removeRightsMinLevel();

            cLevelRights::lockLevelRightsConfigure($level, $sourceRightsId);

        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);

    }


    /**
     * 设置权益数量
     * @param int $level
     * @param int $rights_on
     * @return \Illuminate\Http\JsonResponse
     */
    public function rightsData(int $level, int $sourceRightsId, Request $request)
    {
        $params = $request->all();

        try {

            if (!cLevelRights::canWriteLevelRightsCfg($level, $sourceRightsId)) {
                throw new \Exception('当前操作已锁定，请联系技术人员');
            }

            if (isset($params['name']) && $params['name'] == 'rights_data') {
                $value = $params['value'] ?? 0;
                $value = intval($value);
                $bRet = BrandLevelRightsConfigService::setOneLevelRightsConfigCount($level, $sourceRightsId, $value);
            }
            if (!$bRet) {
                throw new \Exception('权益数量设置失败！');
            }
            $success = [
                'message' => '操作成功',
                'code' => 1,
                'status' => true,
            ];

            cLevelRights::lockLevelRightsConfigure($level, $sourceRightsId);

        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);

    }


    private function setJsScript()
    {
        return <<<SCRIPT
    var obj;
    $('.grid-switch-rights_on').unbind('bootstrapSwitch').bootstrapSwitch({
        size:'mini',
        onText: '开启',
        offText: '关闭',
        onColor: 'primary',
        offColor: 'default',
        onSwitchChange: function(event, state){
            obj = $(this);
            $(this).val(state ? 1 : 0);
            var key = $(this).data('key');
            var value = $(this).val();
            var _status = true;
            var titleArr = new Array();
            titleArr[1] = '确定开启该权益吗？';
            titleArr[0] = '确定关闭该权益吗？';
            swal({
                    title: titleArr[value],
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
            }).then(function(confirm){
                if(confirm.value){
                    $.ajax({
                        url: window.location.pathname + "/switch/" + key,
                        type: "POST",
                        async:false,
                        data: {
                            rights_on: value,
                            action: 'switch',
                            _token: LA.token,
                            _method: 'PUT'
                        },
                        success: function (data) {
                            if (data.status)
                                toastr.success(data.message);
                            else
                                toastr.warning(data.message);
                            setTimeout(function () {
                               $.pjax.reload('#pjax-container');
                            }, 1000);
                        },
                        complete:function(xhr,status) {
                            if (status == 'success')
                                _status = xhr.responseJSON.status;
                        }
                    });
                }else{
                    obj.bootstrapSwitch("state", false);
                }
            });        
            return _status;
        }
    });

SCRIPT;

    }


}